import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:freedom/util/customer_dialog.dart';
import 'package:permission_handler/permission_handler.dart';

class ImageUtil {
  /// 保存图片
  static Future<void> saveWidgetImage(GlobalKey globalKey) async {
    CustomerDialog.loading("保存中...");
    var fileName = DateTime.now()
        .toString()
        .replaceAll(" ", "")
        .replaceAll("-", "")
        .replaceAll(":", "")
        .replaceAll(".", "");
    RenderRepaintBoundary boundary =
        globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage(pixelRatio: 6.0);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData!.buffer.asUint8List();
    if (Platform.isIOS) {
      var status = await Permission.photos.status;
      if (status.isDenied) {
        await [
          Permission.photos,
        ].request();
        saveWidgetImage(globalKey);
      }
      if (status.isGranted) {
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 60, name: fileName);
        if (result != null) {
          CustomerDialog.showText("保存成功");
        } else {
          CustomerDialog.showText("保存失败");
        }
      }
      if (status.isDenied) {
        CustomerDialog.showText("请打开相册访问权限");
      }
    } else if (Platform.isAndroid) {
      var status = await Permission.storage.status;
      if (status.isDenied) {
        await [
          Permission.storage,
        ].request();
        saveWidgetImage(globalKey);
      }
      if (status.isGranted) {
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 60, name: fileName);
        if (result != null) {
          CustomerDialog.showText("保存成功");
        } else {
          CustomerDialog.showText("保存失败");
        }
      }
      if (status.isDenied) {
        CustomerDialog.showText("请打开相册访问权限");
      }
    }
    CustomerDialog.closeAllLoading(groupKey: CustomerDialog.SYSTEM_GROUP);
  }
}
